package org.cerberus.platform.internal.server.queuetest;

import org.mortbay.thread.BoundedThreadPool;
import org.mortbay.thread.ThreadPool;
import org.mortbay.util.IO;

public class TestEventQueue implements Runnable {

	private boolean free;
	
	private Runnable runnable;
	public void postRunnable(Runnable run) {
		this.runnable = run;
		while (runnable != null) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
	}
	
	@Override
	public void run() {
		run(new Conditional() {
			@Override
			public boolean evaluate() {
				return inner1;
			}
		});
	}
	
	public void run(Conditional conditional) {
		System.out.println("Inner in "+conditional.hashCode());
		Thread.dumpStack();
		while (conditional.evaluate()) {
			if (runnable != null) {
				Runnable run = runnable;
				this.runnable = null;
				run.run();
			}
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
		System.out.println("Inner out "+conditional.hashCode());
	}
	
	public void pump(Conditional cond) {
		run(cond);
	}
	
	public void free() {
		this.free = true;
	}
	
	
	public static interface Conditional {
		boolean evaluate();
	}
	
	private ThreadPool pool = new IO() {
		@Override
		protected PoolThread newThread(Runnable job) {
			return super.newThread(job);
		}
	};
	
	private static boolean inner1 = true;
	private static boolean inner2 = true;
	
	public static void main(String[] args) throws Exception {
		BoundedThreadPool pool = new BoundedThreadPool();
		 pool.start();
		final TestEventQueue queue1 = new TestEventQueue();
		pool.dispatch(queue1);
		
		queue1.postRunnable(new Runnable() {
			@Override
			public void run() {
				System.out.println("before pump");
				queue1.pump(new Conditional() {
					@Override
					public boolean evaluate() {
						return inner2;
					}
				});
				System.out.println("after pump");
			}
		});
		
		Thread.sleep(1000);
		
		inner2 = false;
		
		try {
			pool.join();
		} catch (InterruptedException e) {
		}
	}
	
	
}
